package com.xmh.reptile.service;

import cn.hutool.core.io.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UpdateCheckService {

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

    public static final String savePath = "C:\\Users\\xmh\\Desktop\\小说\\save\\";

    @Test
    public void runMain() throws InterruptedException {
        while (true) {
            try {
//                NovelTMDFPService.wgzz();
//                NoveNovtxtService.wgzz();
//                NoveYqxs1Service.wgzz();
//                NoveSodusoService.wgzz();
//                NovelSxu3Service.wgzz();
                NovelLidapolyService.wgzz();
//                NovelQqgwService.qqgw();
//                Novel890HService.qqgw();
                System.out.println(simpleDateFormat.format(new Date()));
                Thread.sleep(1000 * 60 * 60 * 5);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void newRun() throws InterruptedException {
        while (true) {
            try {
//                NovelTMDFPService.wgzz();
//                NoveNovtxtService.wgzz();
                NoveSodusoService.wgzz();
//                NovelSxu3Service.wgzz();
//                NovelService.wgzz();
//                NovelQqgwService.qqgw();
//                Novel890HService.qqgw();
                System.out.println(simpleDateFormat.format(new Date()));
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void updateStyle() {
        String fileName = "李环李长河yqxs12022-02-07 19-29-51";

        String sourcePath = "C:\\Users\\xmh\\Desktop\\小说\\save\\" + fileName + ".txt";
        String targetPath = "C:\\Users\\xmh\\Desktop\\小说\\" + fileName + " new.txt";
        int offset = 44;

//        String newLine = "\n\t";
//        String newLineInsertStr = "\n";
        String newLine = "\n";
        String newLineInsertStr = "\n";

        boolean isInsertNewLine = true;
//        boolean isInsertNewLine = false;

//        String charsetName = "GBK";
        String charsetName = String.valueOf(StandardCharsets.UTF_8);

        String startStr = "“";
        String endStr = "”";
        String str1 = " 【 ";
        String str2 = " 】 ";

        String text = FileUtil.readString(new File(sourcePath), charsetName);

        text = text
                .replace("\r\n", "\n")
                .replace("\n", "\n\n")
                .replace("**使徒", "欲望使徒")
                .replace("李震", "李星河")
                .replace("王怜珊", "阿娇")
                .replace("眉雪", "马儿")
                .replace("    ", "\t")
                .replace("ｍ.soduｓo.cc", "")
                .replace("(https://www.yqxs.cc/html/86340/86340932/110136359.html)", "")
                .replace("请记住本书首发域名：www.yqxs.cc。笔趣阁手机版阅读网址：m.yqxs.cc", "")
                .replace("搜读小说http://ｍ.soｄuso.ｃc ", "")

                .replace("\n", newLine);

        StringBuilder stringBuilder = new StringBuilder();

        for (String str : text.split("\n")) {
            if (StringUtils.isNotEmpty(str)) {

                if (StringUtils.isBlank(str)) {
                    continue;
                }

                String haveUrl = isHaveUrl(str);

                if (haveUrl != null) {
                    System.out.println(haveUrl);
                    str = str.replace("haveUrl", "");
                }

                StringBuilder builder = new StringBuilder(str);

                if (str.contains(startStr) && !str.contains(endStr)) {
                    builder.insert(str.indexOf(startStr), str1);
                }

                if (str.contains(endStr) && !str.contains(startStr)) {
                    builder.insert(str.indexOf(endStr) + 1, str2);
                }

                if (builder.length() > offset && isInsertNewLine) {
                    int lineNumber = builder.length() / offset;
                    for (int index = 1; index <= lineNumber; index++) {
                        int insertOffset = offset;

                        if (index > 1) {
                            insertOffset = builder.lastIndexOf(newLineInsertStr) + offset;

                            if (insertOffset >= builder.length()) {
                                continue;
                            }
                            if (insertOffset + 3 < builder.length()) {
                                insertOffset += 3;
                            }
                        }
                        try {
                            builder.insert(insertOffset, newLineInsertStr);
                        } catch (Exception exception) {
                            exception.printStackTrace();
                        }
                    }
                }
                stringBuilder.append(builder);
            }
            stringBuilder.append("\n");
        }
        String content = stringBuilder.toString();
        content = content.replace("\n\n\n", "\n");
        FileUtil.writeString(content, new File(targetPath), charsetName);
    }

    /**
     * 查询符合的手机号码
     *
     * @param str
     */
    public static String isHaveUrl(String str) {
        String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$";

        // 将给定的正则表达式编译到模式中
        Pattern pattern = Pattern.compile(regex);
        // 创建匹配给定输入与此模式的匹配器。
        Matcher matcher = pattern.matcher(str);
        //查找字符串中是否有符合的子字符串
        if (matcher.find()) {
            return "(" + matcher.group() + ")";
        }
        return null;
    }

    @Test
    public void updateTitle() {
        String sourcePath = "C:\\Users\\xmh\\Desktop\\天命大反派.txt";
        String targetPath = "C:\\Users\\xmh\\Desktop\\天命大反派 Update Title.txt";

        String charsetName = "UTF-8";

        String readString = FileUtil.readString(new File(sourcePath), charsetName);

        StringBuilder builder = new StringBuilder();

        String regex = "\n\t======";
        String[] split = readString.split(regex);
        int i = 65;
        for (String str : split) {
            if (StringUtils.isEmpty(str)) {
                continue;
            }

            builder.append(regex);
            builder.append(" 第").append(i++).append("章 ");
            builder.append(str);
        }
        FileUtil.writeString(builder.toString(), new File(targetPath), charsetName);
    }


    @Test
    public void test4() {
        String targetPath = "C:\\Users\\xmh\\Desktop\\全球高武_对比.txt";
        String charsetName = "UTF-8";

        String source1Path = "C:\\Users\\xmh\\Desktop\\全球高武2.txt";
        String source2Path = "C:\\Users\\xmh\\Desktop\\全球高武_8902.txt";

        String source1 = FileUtil.readString(new File(source1Path), charsetName);
        String source2 = FileUtil.readString(new File(source2Path), charsetName);

        String[] between1 = StringUtils.substringsBetween(source1, "\n\t====== ", " =====\n");
        String[] between2 = StringUtils.substringsBetween(source2, "\n\t====== ", " =====\n");

        Map<String, Object> title1Map = new HashMap<>();
        Map<String, Object> title2Map = new HashMap<>();

        Map<String, Object> map1 = getStringObjectMap(source1, title1Map, between1);
        Map<String, Object> map2 = getStringObjectMap(source2, title2Map, between2);

        StringBuilder sb = new StringBuilder();

        for (int i = 965; i < 1437; i++) {
            sb.append("\n\n\n\n\t====== 第").append(i).append("章 ").append(title1Map.get(i + "")).append(" =====\n\n\n\n");

            Object o = map1.get(i + "");
            if (o == null) {
                Object o1 = map2.get(i + "");
                sb.append((String) o1);
            } else {
                sb.append((String) o);
            }
        }

        FileUtil.writeString(sb.toString(), new File(targetPath), charsetName);
    }

    private Map<String, Object> getStringObjectMap(String source1, Map<String, Object> titleMap, String[] between1) {
        Map<String, Object> map1 = new HashMap<>();

        for (String s : between1) {
            if (s.contains("章") && s.contains("第")) {
                String trim = StringUtils.substringBetween(s, "第", "章").trim();

                String value = StringUtils.substringBetween(source1, "\n\t====== 第" + trim + "章", "\n\n\n\n\t====== ");

                String substring = value.substring(value.indexOf(("=====\n\n\n\n")) + 9);

                map1.put(trim, substring);

                titleMap.put(trim, StringUtils.substringBetween(source1, "\n\t====== 第" + trim + "章 ", " ====="));
            }
        }
        return map1;
    }
}
